package com.CMS.client.ui.view;

import java.util.List;

import com.CMS.client.ItemMenuService;
import com.CMS.client.ItemMenuServiceAsync;
import com.CMS.client.datasource.ItemMenuDataSource;
import com.CMS.client.datasource.MenuDataSource;
import com.CMS.server.domain.ItemMenu;
import com.google.gwt.core.client.GWT;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.smartgwt.client.data.RecordList;
import com.smartgwt.client.types.Alignment;
import com.smartgwt.client.types.HeaderControls;
import com.smartgwt.client.util.SC;
import com.smartgwt.client.widgets.Canvas;
import com.smartgwt.client.widgets.HeaderControl;
import com.smartgwt.client.widgets.ImgButton;
import com.smartgwt.client.widgets.Window;
import com.smartgwt.client.widgets.events.ClickEvent;
import com.smartgwt.client.widgets.events.ClickHandler;
import com.smartgwt.client.widgets.form.DynamicForm;
import com.smartgwt.client.widgets.form.fields.CheckboxItem;
import com.smartgwt.client.widgets.form.fields.SelectItem;
import com.smartgwt.client.widgets.form.fields.TextItem;
import com.smartgwt.client.widgets.grid.ListGrid;
import com.smartgwt.client.widgets.grid.ListGridField;
import com.smartgwt.client.widgets.grid.ListGridRecord;
import com.smartgwt.client.widgets.layout.HLayout;
import com.smartgwt.client.widgets.layout.VLayout;

public class EditItemMenuView extends VLayout{
	private static final String DESCRIPTION = "EditItemMenuView";
	private HLayout rollOverCanvas;  
    private ListGridRecord rollOverRecord;	
    private Window winModal;
    private long id=0;
    private TextItem name;
    private CheckboxItem visible;
    private SelectItem menu;
    private SelectItem item;
    
    public EditItemMenuView(){
    	super();
		
		countryGrid.setShowRollOverCanvas(true);  		  
		  
        countryGrid.setWidth100();  
        countryGrid.setHeight100();  
        countryGrid.invalidateCache();
        countryGrid.setShowAllRecords(true);
        
        ListGridField idField = new ListGridField("id", "Id", 40);  
        ListGridField nameField = new ListGridField("nameMenu", "Name Menu");
        ListGridField itemField = new ListGridField("itemName", "Item");
        ListGridField visibleField = new ListGridField("visibleMenu", "Visible");
        countryGrid.setFields(idField, nameField,itemField, visibleField);  
        countryGrid.setCanResizeFields(true);  
        countryGrid.setData(getRecords());  

        this.addMember(countryGrid);
        this.draw();
    }
    
    private RecordList getRecords(){
		ItemMenuServiceAsync rpc = GWT.create(ItemMenuService.class);
		final RecordList records = new RecordList();
		
		rpc.getItems(new AsyncCallback<List<ItemMenu>>() {
			@Override
			public void onFailure(Throwable caught) {
				// TODO Auto-generated method stub
			}
			@Override
			public void onSuccess(List<ItemMenu> result) {
				for(int i=0; i<result.size(); i++){
					ListGridRecord r = new ListGridRecord();
					r.setAttribute("id", Long.toString(result.get(i).getId()));
					r.setAttribute("nameMenu", result.get(i).getMenu().getDescription());
					r.setAttribute("itemName", result.get(i).getDescription());
					r.setAttribute("visibleMenu", result.get(i).getFlagDelete() == true ? "NO" : "SI" );
					records.add(r);
				}
			}
		});
		return records;
	}
    
    ClickHandler closeHandler = new ClickHandler() {		
		@Override
		public void onClick(ClickEvent event) {
			winModal.hide();
			winModal.destroy();
			winModal = new Window();			
		}
	};
	
	ClickHandler saveHandler = new ClickHandler() {
		@Override
		public void onClick(ClickEvent event) {
			ItemMenuServiceAsync rpc = GWT.create(ItemMenuService.class);
			rpc.updateItem(name.getValueAsString(), id, new Long(menu.getValue().toString()), 
						   (item.getValue() == null) ? 0 : new Long(item.getValue().toString()), 
						   visible.getValueAsBoolean(), new AsyncCallback<Void>() {
							@Override
							public void onFailure(Throwable caught) {
								SC.say(caught.getMessage());
							}
							@Override
							public void onSuccess(Void result) {
								winModal.hide();
								winModal.destroy();
								winModal = new Window();
								countryGrid.setData(getRecords());
							}
						});
		}
	};
    
    final ListGrid countryGrid = new ListGrid() {  
        @Override  
        protected Canvas getRollOverCanvas(Integer rowNum, Integer colNum) {  
            rollOverRecord = this.getRecord(rowNum);  

            HeaderControl save = new HeaderControl(HeaderControl.SAVE, saveHandler);
            HeaderControl close = new HeaderControl(HeaderControl.CLOSE, closeHandler);
            winModal = new Window();              
    		winModal.setTitle("Edit Menu");  
    		winModal.setWidth(350);  
    		winModal.setHeight(200);
    		winModal.setHeaderControls(HeaderControls.HEADER_LABEL,save, close);
    		winModal.setIsModal(true);  
    		winModal.setShowModalMask(true);  
    		winModal.centerInPage();
            
            if(rollOverCanvas == null) {  
                rollOverCanvas = new HLayout(3);  
                rollOverCanvas.setSnapTo("TR");  
                rollOverCanvas.setWidth(50);  
                rollOverCanvas.setHeight(22);  

                ImgButton editImg = new ImgButton();  
                editImg.setShowDown(false);  
                editImg.setShowRollOver(false);  
                editImg.setLayoutAlign(Alignment.CENTER);  
                editImg.setSrc("icons/16/letter.png");  
                editImg.setPrompt("Edit Page");  
                editImg.setHeight(16);  
                editImg.setWidth(16);  
                editImg.addClickHandler(new ClickHandler() {  
                    public void onClick(ClickEvent event) {  
                    	generarEditor(rollOverRecord.getAttribute("id").toString());
                    }  
                });   
                rollOverCanvas.addMember(editImg);  
            }  
            return rollOverCanvas;  
        }  
    };

    private void generarEditor(String id){
    	this.id = new Long(id);
    	name = new TextItem();
    	name.setTitle("Nombre del Item");
    	visible = new CheckboxItem();
    	visible.setTitle("Delete");
    	menu = new SelectItem();
    	menu.setTitle("Men&uacute;");		
		menu.setAccessKey("id");
		menu.setValueField("id");
		menu.setDisplayField("description");
    	menu.setOptionDataSource(new MenuDataSource());
    	item = new SelectItem();
    	item.setTitle("Item Padre");		
		item.setAccessKey("id");
		item.setValueField("id");
		item.setDisplayField("description");
		item.setOptionDataSource(new ItemMenuDataSource());
    	final DynamicForm form = new DynamicForm();
    	form.setWidth(320);
    	form.setIsGroup(true);
    	form.setAlign(Alignment.CENTER);
    	form.setPadding(20);
    	form.setFields(name,menu,item,visible);
    	ItemMenuServiceAsync rpc = GWT.create(ItemMenuService.class);
    	rpc.getItem(this.id, new AsyncCallback<ItemMenu>() {			
			@Override
			public void onSuccess(ItemMenu result) {
				name.setValue(result.getDescription());
				visible.setValue(result.getFlagDelete());
				menu.setValue(result.getMenu().getId());
				item.setValue((result.getPadre() == null) ? null : result.getPadre().getId());
				winModal.addItem(form);
		    	winModal.show();
			}			
			@Override
			public void onFailure(Throwable caught) {
				// TODO Auto-generated method stub				
			}
		});
    }
    
    public static class Factory implements ContextAreaFactory{
		private String id;
		 
		public Canvas create(){
			//hay que crear la vista que vamos a llamar
			EditItemMenuView view = new EditItemMenuView();
			id = view.getID();
			return view;
	    }
		 
		public String getID(){
			return id;
		}

		public String getDescription(){
			return DESCRIPTION;
		}
	 }
}
